﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Jinx.Naming.Paths
{
    public class Path : IEnumerable<IPathNode>
    {
        private readonly IEnumerable<IPathNode> Nodes;

        public Path(IEnumerable<IPathNode> Path)
        {
            Nodes = Path;
        }

        public string PathString
        {
            get
            {
                var PathElements = (from Node in this
                                    select Node.PathElement).ToArray();

                return string.Concat(PathElements);
            }
        }

        #region IEnumerable<IPathNode> Members

        public IEnumerator<IPathNode> GetEnumerator()
        {
            return Nodes.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (this as IEnumerable<IPathNode>).GetEnumerator();
        }

        #endregion

        #region Overrides

        public override int GetHashCode()
        {
            var Hash = 0;
            foreach (var Node in Nodes)
                Hash += Node.GetHashCode();
            return Hash;
        }

        public override bool Equals(object obj)
        {
            var ThatPath = obj as Path;

            if (ThatPath != null)
                return this.SequenceEqual(ThatPath);
            
            return false;
        }

        public override string ToString()
        {
            var NodeStrings = from Node in Nodes select Node.ToString();
            return string.Concat(NodeStrings.ToArray());
        }

        #endregion

        public bool IsPrefix(Path Path)
        {
            var ThisCount = this.Count();

            if (ThisCount <= Path.Count())
                return this.SequenceEqual(Path.Take(ThisCount));
            
            return false;
        }
    }
}